package com.zzw.resilience4j;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;

import java.time.Duration;

/**
 * @author Administrator
 */
public class DefaultRes4jRateLimter implements Res4jRateLimterFactory {

    @Override
    public Res4jRateLimter createRes4JRateLimter(String id
            , Duration limitRefreshPeriod, int limitForPeriod, Duration timeoutDuration) {
        RateLimiterConfig config = RateLimiterConfig.custom()
                .limitRefreshPeriod(limitRefreshPeriod)
                .limitForPeriod(limitForPeriod)
                .timeoutDuration(timeoutDuration)
                .build();
        RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.of(config);
        RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter(id, config);
        return new DefaultRes4j(rateLimiter);
    }

    public static class DefaultRes4j implements Res4jRateLimter {

        private final RateLimiter rateLimiter;

        public DefaultRes4j(RateLimiter rateLimiter) {
            this.rateLimiter = rateLimiter;
        }

        @Override
        public boolean allowed() {
            return rateLimiter.acquirePermission();
        }
    }
}
